package com.hcinfos.gsoo.util;

import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.User;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class LoginUtil {

	public static final int LOGIN_FAIL = 0x9900;
	public static final int LOGIN_SUCCESS = LOGIN_FAIL + 1;

	public static void isLoginSuccess(Context context, final Handler handler) {

		SharePreferenceUtil util = new SharePreferenceUtil(context, "setting");
		User user = (User) util.loadObject("user");
		if (user == null) {
			handler.sendEmptyMessage(LoginUtil.LOGIN_FAIL);
			return;
		}
		String password = util.loadStringSharedPreference("password");
		String loginName = user.getEmail() == null ? user.getGgnumber() : user
				.getEmail();
		HttpUtils http = UtilHttp.getHttpUtils(context);
		RequestParams params = new RequestParams();
		params.addBodyParameter("user.email", loginName);
		params.addBodyParameter("user.password",
				user.getPassword() == null ? password : user.getPassword());
		http.send(HttpRequest.HttpMethod.POST, Urls.NEW_USER_LOGIN, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Log.e("wxf", arg0.toString());
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {

						String result = text.result;
						Log.d("wxf", "login=" + text.result);
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(LOGIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(LOGIN_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(LOGIN_FAIL);
							Log.e("wxf", e.toString());
						}

					}

				});

	}
}
